package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.exceptios.LyException;
import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.entity.SpecGroup;
import com.leyou.item.mapper.SpecGroupMapper;
import com.leyou.item.service.SpecGroupService;
import com.leyou.item.service.SpecParamService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 虎哥
 */
@Service
public class SpecGroupServiceImpl extends ServiceImpl<SpecGroupMapper, SpecGroup> implements SpecGroupService {

    private final SpecParamService paramService;

    public SpecGroupServiceImpl(SpecParamService paramService) {
        this.paramService = paramService;
    }

    @Override
    public List<SpecGroupDTO> querySpecList(Long id) {
        // 1.查询规格组
        List<SpecGroup> groupList = query().eq("category_id", id).list();
        // 1.1.转DTO
        List<SpecGroupDTO> groupDTOList = SpecGroupDTO.convertEntityList(groupList);
        // 1.2.健壮性
        if(CollectionUtils.isEmpty(groupDTOList)){
            // 没查询到，返回404
            throw new LyException(404, "规格参数不存在！");
        }

        // 2.查询所有参数
        List<SpecParamDTO> paramList = paramService.queryParams(null, id, null);
        // 健壮性
        if(CollectionUtils.isEmpty(paramList)){
            // 没查询到，返回404
            throw new LyException(404, "规格参数不存在！");
        }

        // 3.把groupDd一致的param放到一起，人为分组放到一个Map,key是groupId，值是groupId一致的param的集合
        Map<Long, List<SpecParamDTO>> map = paramList.stream().collect(Collectors.groupingBy(SpecParamDTO::getGroupId));
        // 给规格组中添加参数
        for (SpecGroupDTO groupDTO : groupDTOList) {
            // 根据组id查询组内参数
            List<SpecParamDTO> params = map.get(groupDTO.getId());
            // 放入group
            groupDTO.setParams(params);
        }
        return groupDTOList;
    }
}